package com.imooc.sell.controller;

import com.imooc.sell.dataobject.ProductCategory;
import com.imooc.sell.dataobject.ProductInfo;
import com.imooc.sell.enums.ProductStatusEnum;
import com.imooc.sell.service.ProductCategoryService;
import com.imooc.sell.service.ProductInfoService;
import com.imooc.sell.utils.ResultVoUtil;
import com.imooc.sell.vo.ProductInfoVo;
import com.imooc.sell.vo.ProductVo;
import com.imooc.sell.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private ProductInfoService productInfoService;

    @GetMapping("/list")
    public ResultVo doGetList(){
        //1.查询基础数据(商品及其分类信息)
        List<ProductInfo> productInfoList=productInfoService.findByProductStatus(ProductStatusEnum.UP.getCode());
        List<Integer> categoryTypeList=productInfoList.stream().map(ProductInfo::getCategoryType).distinct().collect(Collectors.toList());
        if(categoryTypeList.size()==0){
            return ResultVoUtil.error(1,"无有效分类");
        }
        List<ProductCategory> productCategoryList=productCategoryService.findByCategoryTypeIn(categoryTypeList);

        //2.处理包装
        List<ProductVo> productVoList=productCategoryList.stream().map(o->{
            ProductVo productVo=new ProductVo();
            BeanUtils.copyProperties(o,productVo);
            List<ProductInfoVo> productInfoVoListEach=productInfoList.stream()
                    .filter(o2->o2.getCategoryType().equals(o.getCategoryType()))
                    .map(o2->{
                      ProductInfoVo productInfoVo=new ProductInfoVo();
                      BeanUtils.copyProperties(o2,productInfoVo);
                      return productInfoVo;
                    })
                    .collect(Collectors.toList());
            productVo.setProductInfoVoList(productInfoVoListEach);
            return productVo;
        }).collect(Collectors.toList());

        //3.返回结果

        return ResultVoUtil.success(productVoList);
    }
}
